import type { ObjectDirective } from 'vue'

interface IBlur extends HTMLInputElement {
  _touchHandle(event: Event): void
}

const map = new WeakMap()

const onTouchStart = (element: HTMLElement, event: Event) => {
  if (element !== event.target) {
    element.blur()
  }
}

const onInputFoucs = (event: Event) => {
  const element = event.target as IBlur
  element._touchHandle = onTouchStart.bind(window, element)
  window.addEventListener('touchstart', element._touchHandle, true)
  window.addEventListener('touchmove', element._touchHandle, true)
  window.addEventListener('touchend', element._touchHandle, true)
}

const onInputBlur = (event: Event) => {
  const element = event.target as IBlur
  window.removeEventListener('touchstart', element._touchHandle, true)
  window.removeEventListener('touchmove', element._touchHandle, true)
  window.removeEventListener('touchend', element._touchHandle, true)
}

const Blur: ObjectDirective = {
  mounted(el: HTMLElement) {
    let element = null
    // 判断el是否为input textarea元素
    if (el.tagName.toLowerCase() !== 'input' || el.tagName.toLowerCase() !== 'textarea') {
      element = el.querySelector('input') ? el.querySelector('input') : el.querySelector('textarea')
    } else {
      element = el
    }
    map.set(el, element)
    if (element) {
      element.addEventListener('focus', onInputFoucs)
      element.addEventListener('blur', onInputBlur)
    }
  },
  unmounted(el: HTMLElement) {
    const element = map.get(el)
    if (element) {
      element.removeEventListener('focus', onInputFoucs)
      element.removeEventListener('blur', onInputFoucs)
    }
  }
}

export default Blur
